package com.googlecode.h0v3rk4rt.graphics;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.Timer;

import com.googlecode.h0v3rk4rt.core.h0v3rk4rt;
import com.googlecode.h0v3rk4rt.net.MultiplayerClient;

public class Multiplayer extends JFrame {

	/**
	 * default ID
	 */
	private static final long serialVersionUID = 1L;
	private static DrivePanel panel;
	private static String host;
	private static Multiplayer game;
	static Timer clientUpdate;
	public static boolean shutdown;
	private static h0v3rk4rt source;

	public static void main(String... args) {
		startDrivingGame("127.0.0.1", null);
	}

	public static void startDrivingGame(String host, h0v3rk4rt s) {
		shutdown = false;
		MultiplayerClient.shutdown = false;
		Multiplayer.host = host;
		source = s;
		game = new Multiplayer("h0v3rk4rt Client");
		startClient();
	}

	public Multiplayer(String title) {
		super(title);
		try {
			initialize();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void initialize() throws IOException {
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				shutdown(null);
			}
		});
		panel = new DrivePanel(800, 500);
		getContentPane().add(panel);
		pack();
		setVisible(true);
		clientUpdate = new Timer(25, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				repaint();
			}
		});
		clientUpdate.start();
		panel.requestFocus();
	}

	private static void startClient() {
		MultiplayerClient.start(host);
	}
	
	public static void shutdown(String s) {
		System.out.println("Game trying to shut down.");
		if(shutdown) return;
		System.out.println("Game shutting down.");
		shutdown = true;
		MultiplayerClient.shutdown();
		clientUpdate.stop();
		clientUpdate = null;
		game.setVisible(false);
		game.dispose();
		game = null;
		panel.shutdown();
		panel = null;
		if(source != null) {
			source.startAgain(s);
		} else System.out.println("FFFUUU");
	}
}